import React from 'react';
import { Result, Button } from 'antd';

interface ErrorBoundaryState {
  hasError: boolean;
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<{}>, ErrorBoundaryState> {
  constructor(props: React.PropsWithChildren<{}>) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(): ErrorBoundaryState {
    return { hasError: true };
  }

  componentDidCatch(error: any, errorInfo: any) {
    // 这里可以上报错误日志
    // console.error('ErrorBoundary caught:', error, errorInfo);
  }

  handleRetry = () => {
    // 简单恢复策略：刷新页面
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 24 }}>
          <Result
            status="error"
            title="页面加载失败"
            subTitle="抱歉，加载页面时出现错误。您可以尝试刷新。"
            extra={
              <Button type="primary" onClick={this.handleRetry}>
                刷新重试
              </Button>
            }
          />
        </div>
      );
    }

    return this.props.children as React.ReactElement;
  }
}

export default ErrorBoundary;